﻿using System;
using System.Configuration;
using System.Reflection;
using TeamCommunitySolution.Domain.DataLayer;

namespace TeamCommunitySolution.Services.Factories {
  public class NHSessionFactory {
    /// <summary>
    /// internal holder.
    /// </summary>
    private static NHibernate.Cfg.Configuration _cfg = null;

    /// <summary>
    /// internal holder.
    /// </summary>
    private static NHibernate.ISessionFactory _sessionFactory = null;

    /// <summary>
    /// Gets the factory.
    /// </summary>
    /// <value>The factory.</value>
    public static NHibernate.ISessionFactory Factory {
      get {
        if(_cfg == null) {
          _cfg = GetConfig();
        }

        if(_sessionFactory == null) {
          _sessionFactory = _cfg.BuildSessionFactory();
        }

        return _sessionFactory;
      }
    }

    /// <summary>
    /// Gets the config.
    /// </summary>
    /// <returns>NHibernate Configuration</returns>
    private static NHibernate.Cfg.Configuration GetConfig() {
      _cfg = new NHibernate.Cfg.Configuration();
      _cfg.Configure();

      String location = Assembly.GetAssembly(typeof(ConfigurationPointer)).Location;

      if(!System.IO.File.Exists(location)) {
        throw new Exception("Unable to find the hibernate data definition in the NHSessionFactory");
      }

      _cfg.AddAssembly(Assembly.LoadFrom(location));

      
      return _cfg;
    }
  }
}
